<template>
  <!-- 顶部导航 -->
  <van-nav-bar title="订单确认" left-arrow left-text="返回" @click-left="onClickLeft"></van-nav-bar>
  <!-- 主体部分 -->
  <div class="container">
    <!-- 地址区域 -->
    <div class="address-card" @click="handlePopup">
      <p class="info">
        <span class="username" v-text="defaultAddress.name"></span>
        <span class="phone" v-text="defaultAddress.tel"></span>
      </p>
      <p class="address">
        <span class="default" v-if="defaultAddress.isDefault">[默认]</span>
        <span class="user-adress" v-text="defaultAddress.address"></span>
      </p>
    </div>
    <!-- 弹出层 -->
    <van-popup v-model:show="show" position="bottom">
      <van-address-list
        v-model="chosenAddressId"
        :list="addressList"
        default-tag-text="默认"
        @click-item="changeAddress"
        @add="onAdd"
        @edit="onEdit">
        <template #top v-if="isEmpty">
          <!-- 地址为空时显示内容 -->
          <van-empty description="请添加地址~"></van-empty>
        </template>
      </van-address-list>
    </van-popup>
    <!-- 商品列表 -->
    <div class="product-list">
      <!-- 标题 -->
      <van-cell-group>
        <van-cell>共{{carNum}}件</van-cell>
      </van-cell-group>
      <!-- 列表 -->
      <van-cell-group v-for="item in cartInfo" :key="item.id">
        <van-cell class="product">
          <img :src="item.productInfo.image">
          <div class="info">
            <p class="title" v-text="item.productInfo.store_name"></p>
            <p class="price">￥{{item.truePrice}}</p>
          </div>
          <span class="count">X{{item.cart_num}}</span>
        </van-cell>
      </van-cell-group>
    </div>
  </div>
  <!-- 底部立即付款 -->
  <van-submit-bar label="订单总计：" :price="totalPrice"  button-text="立即付款"
  @click="showPopup" />
  <!-- 立即付款弹出层 -->
  <!-- <van-popup v-model:show="payShow"></van-popup> -->
    <van-action-sheet
      v-model:show="payShow"
      :actions="actions"
      cancel-text="取消"
      title="请选择支付方式">
      <!-- 付款列表 -->
        <template #default>
          <van-radio-group v-model="paymethod" checked-color="#ee0a24">
            <van-cell-group>
              <!-- 微信支付 -->
              <van-cell clickable title="微信支付" label="微信快捷支付" @click="paymethod = 'WeChat'" center="">
                <template #icon>
                  <van-icon name="wechat-pay" color="green" size="30" style="margin-right:10px" />
                </template>
                <template #right-icon>
                  <van-radio name="WeChat" />
                </template>
              </van-cell>
              <!-- 支付宝支付 -->
              <van-cell clickable title="支付宝保支付" label="支付宝快捷支付" @click="paymethod = 'alipay'" center="">
                <template #icon>
                  <van-icon name="alipay" color="blue" size="30" style="margin-right:10px" />
                </template>
                <template #right-icon>
                  <van-radio name="alipay" />
                </template>
              </van-cell>
               <!-- 余额支付 -->
               <van-cell clickable title="余额支付" :label="`可用余额为:${nowmoney}元`" @click="paymethod = 'yue'" center="">
                <template #icon>
                  <van-icon name="card" color="orange" size="30" style="margin-right:10px" />
                </template>
                <template #right-icon>
                  <van-radio name="yue" />
                </template>
              </van-cell>
              <!-- 去支付 -->
              <van-cell>
                <van-button type="danger" round block @click="handlePay">立即支付</van-button>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
        </template>
    </van-action-sheet>
</template>
<script setup>
import { NavBar as VanNavBar, Button as VanButton, 
  CellGroup as VanCellGroup, Cell as VanCell, Popup as VanPopup,
  Empty as VanEmpty, AddressList as VanAddressList, SubmitBar as VanSubmitBar,
  ActionSheet as VanActionSheet, RadioGroup as VanRadioGroup,
  Icon as VanIcon, Radio as VanRadio } from 'vant'
import { computed, ref } from 'vue'
import { getAddress, getOrderConfirm, createOrder } from '@/api/order.js'
import { Toast } from 'vant';
import { useRoute, useRouter } from 'vue-router';
const router = useRouter()
const route = useRoute()



// 顶部返回按钮
const onClickLeft = () =>{
  router.push({
    name: 'car' 
  })
}


//-------- 地址区域 --------  
// --弹出层显示状态
const show = ref(false)
// --点击触发弹出层
const handlePopup =  () => {
  show.value = true
}

// --选中状态 地址id
const chosenAddressId = ref('')
// --点击任意地址 
const changeAddress = item => {
  // 关闭弹出层
  show.value = false,
  // 将默认地址改为当前地址 item: AddressListAddress,
  defaultAddress.value = item
}

// --地址数据
const addressList = ref([])
// 默认地址
const defaultAddress = ref({})
// 判段地址是否为空
const isEmpty = computed(() => addressList.value.length === 0)


// 得到的data是数组在请求数据之前先做数据转换
const convertData = data => {
  return data.map(item => {
    const temp = {
      id: item.id,
      name: item.real_name,
      tel: item.phone,
      address: item.province + item.city + item.district + item.detail,
      isDefault: item.is_default
    }

    // 检测是否为默认选中数据  弹出层的默认地址
    if (item.is_default === 1){
      chosenAddressId.value = item.id
      defaultAddress.value = temp
    }
    return temp
  })

}
// --获取用户收件地址
const initAddress = async () => {
  const { data } = await getAddress({
    page: 1,
    limit: 5
  })
  // console.log(data)
  if (data.status !== 200){ return }
  addressList.value = convertData(data.data)
}
initAddress()

// --新增地址
// 接受传值
// const { carId } = defineProps({
//   carId: {
//     type: String,
//     required: true
//   }
// })
const carId = route.query.carId
const onAdd = () => { router.push({
  // 在新增完页面之后要返回到确认订单页面 需要传递carId
  name: 'address',
  query: {
    carId
  }
})
}
// --编辑
const onEdit = (item, index) => Toast('编辑地址:' + index);



//  ------  初始化订单页面 ------
//存储数据订单页面的详细数据
const OrderConfirmData = ref({})
// 计算属性处理数据
const cartInfo = computed(() => OrderConfirmData.value?.cartInfo )
const carNum = computed(()=> cartInfo.value?.length || 0)
const totalPrice = computed(()=> (OrderConfirmData.value?.priceGroup?.totalPrice || 0) * 100)

const initOrderConfirm = async () =>{
  const {data} = await getOrderConfirm({
    cartId: carId,
    new: 0
  })
  console.log(data)
  OrderConfirmData.value = data.data 
}
initOrderConfirm()


// -------  支付页面弹出层 -----

// 弹出层显示状态
const payShow = ref(false)
// 支付方式
const paymethod = ref('yue')
const nowmoney = computed(()=> OrderConfirmData.value?.userInfo?.now_money || 0)
const orderKey = computed(()=> OrderConfirmData.value?.orderKey)
const showPopup = () =>{
  payShow.value  = true
}
const handlePay = async () =>{
  const { data } = await createOrder(OrderConfirmData.value?.orderKey, {
    addressId: defaultAddress.value.id,
    payType: paymethod.value 
  })
  // console.log(data)
  if (data.status !==200){return}
  // 提示并跳转到详情页
  Toast.success('支付成功')
  router.push({
    name: 'orderDetail'
  })
}
</script>
<style lang='scss' scoped>
.van-nav-bar{
  position: fixed !important;
  width: 100%;
}
.container{
  padding: 50px 0;
  // 地址卡片
  .address-card{
    padding: 20px 25px;
    font-size: 16px;
    position: relative;
    &::after {
      content: '';
      position: absolute;
      left: 0;
      bottom: 0;
      right:0;
      height: 2px;
      background: repeating-linear-gradient(90deg, #ff6c6c 0, #ff6c6c 20%, transparent 20%, transparent 25%, #0084ff 25%, #0084ff 45%, transparent 45%, transparent 50%);
      background-size: 80px;
    }
    .info{
      margin-bottom: 6px;
      .username{
        padding-right: 30px;
      }
    }
    .address{
      .default{
        background-color: rgb(233, 10, 10);
        margin-right: 20px;
        color: #fff;
        padding: 2px;
        border-radius: 2px;
      }
    }
  }
  // 商品列表
  .product-list{
    :deep(.van-cell__value){
      display: flex;
      align-items: center;
      width: 100%;
      padding: 0;

      img{
        width: 70px;
        height: 70px;
        margin-right: 10px;
      }

      .info{
        width: 100%;
        padding-left: 5px;
        .title{
          display: -webkit-box;
          -webkit-box-orient:vertical;
          -webkit-line-clamp: 1;
          overflow: hidden;
          padding: 0 15px 0 0;
        }
        .price{
          color: #fd3b3b;
          padding-top: 15px;
        }

      }
      .count{
        color: #999;
      }
    }
  }
}

</style>
